import { methodPostApi, methodGetApi, uploadFile } from '@/api/publicApi'
import {downFileATag, downFileBlobATag, getDownLoadFile} from '@/utils/commonUtils/zipdownload.js'
import { returnPath } from '@/utils/commonUtils/HLUtils'
// 依赖
import { Base64 } from 'js-base64'
export const uploadMixins = {
  data() {
    return {
      fileMd5: null,
      chunkCount: 0,
      fileData: null,
      chunkSize: 10 * 1024 * 1024,
      jumpNums: 0
    }
  },
  inject: {
    processProvide: {
      default: () => ({})
    }
  },
  methods: {
    // 上传附件
    requestFileFun(file, fileList, fileSizeType) {
      console.log(this.dateTiem)
      console.log(this.dateTiemName)
      if (this.dateTiem) {
        var a = (Date.parse(this.dateTiem) - Date.parse(this.getTimeDate('year-month-date'))) / 3600 / 1000
        if (a < 0) {
          this.msgAlt(`${this.dateTiemName}已过期,请重新认证后再上传`, 'warning')
          this.$refs['upload'].clearFiles()
          return false
        } else {
          this.requestFileYzFun(file, fileList, fileSizeType)
        }
      } else {
        this.requestFileYzFun(file, fileList, fileSizeType)
      }
    },
    requestFileYzFun(file, fileList, fileSizeType) {
      const fileData = {
        'deptName': encodeURI(this.$store.state.user.userInfo.deptName),
        'createName': encodeURI(this.$store.state.user.userInfo.username)
      }
      const fileNewName = file.file.uid + '.' + file.file.name.substr(file.file.name.lastIndexOf('.') + 1)
      fileData.annexName = encodeURI(file.file.name)
      fileData.downAnnexName = encodeURI(fileNewName)
      fileData.annexSize = file.file.size
      fileData.downAnnexType = file.file.type
      // fileData.projectInfoId = this.$store.state.projectInfo.projectInfo.id
      fileData.routerPath = this.$router.app._route.path
      // ("--------走2")
      if (file.size >= 50 * 1024 * 1024) {
        this.uploadLargeFile(file, fileData, this.filesNum++, this.filesListTagePicBool, this.changeUploadBool, this.limit, this.earlyBool, 'large')
      } else {
        this.uploadFileFun(file, fileData, this.filesNum++)
      }

      this.$refs['upload'].clearFiles()
    },
    changeFile(files, fileList, fileSizeType) {
      this.newFileLength = fileList.length
      fileList.forEach(file => {
        if (file.size > 0 && file.size <= 1024 * 1024 * 1024) {
          this.fileAccept = true
          var index = file.name.lastIndexOf('.')
          // 获取后缀
          var ext = file.name.substr(index + 1).toLowerCase()
          let extBool = false
          // let extArray=['png','jpg','jpeg','bmp','doc','docx','xls','xlsx','rar','war','zip','pdf','ppt','pptx','dwg','dxf','dwt','dws','bim','rvt','txt'];
          let extArray = ['rtf', 'tif', 'png', 'jpg', 'jpeg', 'bmp', 'doc', 'docx', 'xls', 'xlsx', 'rar', 'war', 'zip', '7z', 'arj', 'z', 'pdf', 'ppt', 'bak', 'pptx', 'dwg', 'dxf', 'dwt', 'dws', 'bim', 'rvt', 'txt', 'mov', 'rmvb', 'mp4']// 包括视频
          if (this.videoFiles) {
            extArray = ['png', 'jpg', 'jpeg', 'mov', 'rmvb', 'mp4']// 包括视频
          }
          extArray.forEach(element => {
            if (element === ext) {
              extBool = true
            }
          })

          if (!extBool) {
            this.newFileLength = this.newFileLength - 1
          } else {
            // 输出结果
            this.fileAccept = true
            if (this.sentencedEmpty(this.accept)) {
              var extarr = this.accept
              if (extarr.indexOf(ext) === -1) {
                this.newFileLength = this.newFileLength - 1
              }
            }
          }
        } else {
          if (file.size > 1024 * 1024 * 1024) {
            this.newFileLength = this.newFileLength - 1
          } else {
            this.newFileLength = this.newFileLength - 1
          }
        }
      })
    },
    // 附件校验
    beforeUpload(files, fileSizeType) {
      const file = files.file
      if (file.size > 0 && file.size <= 1024 * 1024 * 1024) {
        this.fileAccept = true
        var index = file.name.lastIndexOf('.')
        // 获取后缀
        var ext = file.name.substr(index + 1).toLowerCase()
        let extBool = false
        // let extArray=['png','jpg','jpeg','bmp','doc','docx','xls','xlsx','rar','war','zip','pdf','ppt','pptx','dwg','dxf','dwt','dws','bim','rvt','txt'];
        let extArray = ['rtf', 'tif', 'png', 'jpg', 'jpeg', 'bmp', 'doc', 'docx', 'xls', 'xlsx', 'rar', 'war', 'zip', '7z', 'arj', 'z', 'pdf', 'ppt', 'bak', 'pptx', 'dwg', 'dxf', 'dwt', 'dws', 'bim', 'rvt', 'txt', 'mov', 'rmvb', 'mp4']// 包括视频
        if (this.videoFiles) {
          extArray = ['png', 'jpg', 'jpeg', 'mov', 'rmvb', 'mp4']// 包括视频
        }
        extArray.forEach(element => {
          if (element === ext) {
            extBool = true
          }
        })

        if (!extBool) {
          this.fileAccept = false
          this.msgAlt(`请上传正确的文件格式`, 'warning')
          return false
        } else {
          // 输出结果
          this.fileAccept = true
          if (this.sentencedEmpty(this.accept)) {
            var extarr = this.accept
            if (extarr.indexOf(ext) === -1) {
              this.fileAccept = false
              this.msgAlt(`文件后缀为${this.accept}格式的附件!`, 'error')
              return false
            }
          }
        }
      } else {
        if (file.size > 1024 * 1024 * 1024 * 10) {
          this.msgAlt('请上传小于10GB的文件', 'error')
          this.fileAccept = false
          return false
        } else {
          this.msgAlt('请上传有效文件', 'error')

          this.fileAccept = false
          return false
        }
      }
      return true
    },
    resetProcessFun() {
      this.filesProcessDialog = false
      this.filesProcessList = []
      this.successData = []
      this.filesNum = 0
    },
    // 附件
    uploadFileFun(
      fileObj,
      fileData,
      fileIndex,
      picCardBool,
      dialogUploadBool,
      limit,
      earlyBool
    ) {
      this.filesProcessDialog = true // 进度条弹框
      this.filesProcessList.push(fileData) // 进度条数据
      const file = fileObj.file
      var oMyForm = new FormData()
      // oMyForm.append('projectId', fileData.projectInfoId)
      // oMyForm.append('businessType', fileData.businessType)
      oMyForm.append('fileType', fileData.downAnnexType)
      oMyForm.append('file', file)
      oMyForm.append('fileSize', fileData.annexSize)
      oMyForm.append('fileName', fileData.annexName)
      // oMyForm.append('flowCode', fileData.flowCode)
      methodPostApi('/sys/annex/handleFileUpload', oMyForm).then((res) => {
        if (res.code === 9000) {
          // returnPath(res.data.annexPath).then((ress) => {
          //   res.data.newAnnexPath = ress
          // })
          this.$emit('getFileList', res.data)
          this.filesProcessList.forEach((element, indexFiles) => {
            if (fileIndex === indexFiles) {
              this.$set(this.filesProcessList[indexFiles], 'percentageFiles', 100)
              this.$set(this.filesProcessList[indexFiles], 'statusFiles', 'success')
            }
          })
        } else {
          this.msgAlt('上传失败', 'error')
        }
      }).catch((error) => {
        this.msgAlt('上传失败', 'error')
      })
    },
    // 超大附件
    uploadLargeFile(
      fileObj,
      fileData,
      fileIndex,
      picCardBool,
      dialogUploadBool,
      limit,
      earlyBool
    ) {
      if (fileIndex == 0) {
        this._data.successData = []
        this.filesProcessList = []
      }
      const fileSize = fileData.annexSize
      this.chunkCount = Math.ceil(fileSize / this.chunkSize) // 分片切割数
      const i = 0
      fileData.percentageFiles = 0
      fileData.statusFiles = null
      this.filesProcessDialog = true
      this.filesProcessList.push(fileData)
      this.shardUpload(
        i,
        this.chunkCount,
        fileSize,
        fileObj,
        fileData,
        fileIndex,
        picCardBool,
        dialogUploadBool,
        limit,
        earlyBool
      )
    },
    // 分片上传
    shardUpload(
      i,
      chunkCount,
      fileSize,
      fileObj,
      fileData,
      fileIndex,
      picCardBool,
      dialogUploadBool,
      limit,
      earlyBool
    ) {
      const file = fileObj.file
      if (i + 1 != chunkCount) {
        this.filesProcessList.forEach((element, indexFiles) => {
          if (fileIndex == indexFiles) {
            if (
              Math.round((Number(i + 1) / Number(this.chunkCount)) * 10000) /
                            100.0 >=
                            100
            ) {
              element.percentageFiles = 100
              element.statusFiles = 'success'
            } else {
              element.percentageFiles =
                                Math.round((Number(i) / Number(this.chunkCount)) * 10000) /
                                100.0
            }
          }
        })
      }
      return new Promise((resolve, reject) => {
        const end =
                    (i + 1) * this.chunkSize >= fileSize
                      ? fileSize
                      : (i + 1) * this.chunkSize
        const _formData = new FormData() // 构造表单
        const shardfiles = file.slice(i * this.chunkSize, end)
        _formData.append('file', shardfiles) // 切出文件的一部分
        // _formData.append('projectId', fileData.projectInfoId)
        _formData.append('chunks', chunkCount)
        _formData.append('chunk', i)
        _formData.append('name', file.name)
        // _formData.append('flowCode', fileData.flowCode)
        _formData.append('guid', file.uid)
        // _formData.append('businessType', fileData.businessType)
        uploadFile(_formData).then((res) => {
          i++
          if (res.code == 9000) {
            if (i == chunkCount) {
              this.filesMergeFun(
                file.uid,
                fileData.projectInfoId,
                fileSize,
                fileData.businessType,
                fileData.downAnnexType,
                fileIndex,
                picCardBool,
                dialogUploadBool,
                limit,
                earlyBool,
                fileData.annexName
              )
            } else {
              this.shardUpload(
                i,
                this.chunkCount,
                fileSize,
                fileObj,
                fileData,
                fileIndex,
                picCardBool,
                dialogUploadBool,
                limit,
                earlyBool
              )
            }
          }
        })
      })
    },
    // 合并附件
    filesMergeFun(
      fileId,
      projectInfoId,
      fileSize,
      businessType,
      downAnnexType,
      fileIndex,
      picCardBool,
      dialogUploadBool,
      limit,
      earlyBool,
      fileName
    ) {
      const _formData = new FormData() // 构造表单
      _formData.append('guid', fileId) // 切出文件的一部分
      _formData.append('projectId', projectInfoId)
      _formData.append('fileSize', fileSize)
      _formData.append('businessType', businessType)
      _formData.append('fileType', downAnnexType)
      _formData.append('fileName', fileName)
      methodPostApi('/sys/annex/mergeAll', _formData)
        .then((res) => {
          if (res.code === 9000) {
            returnPath(res.data.annexPath).then((ress) => {
              res.data.newAnnexPath = ress
            })
            console.log(res.data)
            this.$emit('getFileList', res.data)
            this.filesProcessList.forEach((element, indexFiles) => {
              if (fileIndex === indexFiles) {
                this.$set(this.filesProcessList[indexFiles], 'percentageFiles', 100)
                this.$set(this.filesProcessList[indexFiles], 'statusFiles', 'success')
              }
            })
          } else {
            this.msgAlt('上传失败', 'error')
          }
        })
    },

    /**
     * @description: 预览文件
     * @author: 张佳敏
     * @param {*} row 附件值
     * @return {*}
     */
    LookFileViewFun(row) {
      if (row && row.annexPath) {
        window.open(process.env.VUE_APP_FILES_PREVIEW + encodeURIComponent(Base64.encode(row.annexPath)))
        // window.open('http://123.249.71.109:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode('http://123.249.71.109:80/prod-api/virtual/agencyAffairsSupport/34de3ffca05a3c53d77ed243d1af43cb/升辉工挖机租赁合同（240000元）.docx')))
      }
    },

    /**
     * @description: 下载文件
     * @author: 张佳敏
     * @param {*} row 附件值
     * @return {*}
     */
    downLoadFileFun(row) {
      this.msgAlt('正在下载,请稍后...', 'success')
      if (this.isImage(this.isFileChinaNameBack(row.annexName))) {
        downFileBlobATag(row)
      } else {
        downFileATag(row)
      }
    },

    /**
     * @description:
     * @Author: 张佳敏
     * @param {*} row 附件值
     * @param {*} filesList //当前附件的Array
     * @return {*}
     */
    deleteFileFun(row, filesList) {
      const data = {
        ids: row.id
      }
      methodGetApi('/sys/annex/removeByIds', data).then((res) => {
        if (res.code == 9000) {
          filesList.forEach((element, index) => {
            if (element.id === row.id) {
              this.$emit('deleteFileList', element, '')
            }
          })
          this.msgAlt('删除成功', 'success')
        } else {
          this.msgAlt('删除失败', 'error')
        }
      }).catch((error) => {
        console.log(error)
        this.msgAlt('删除失败', 'error')
      })
    }
  }
}
